package com.system.login.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;


@Controller
public class EmailControllelr {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private DefaultKaptcha kaptcha;

    @RequestMapping(path = "/send/email")
    @ResponseBody
    public String send(HttpSession session) {

        MimeMessage message1 = javaMailSender.createMimeMessage();


        try {

            MimeMessageHelper helper = new MimeMessageHelper(message1, true);

            String code = kaptcha.createText();//创建随机数字
            session.setAttribute("emailcode", code);
            helper.setFrom("19851623191@163.com");
            helper.setTo("19851623191@163.com");
            helper.setSubject("主题：验证码");
            message1.setText("<h1>" + code + "</h1>", "utf-8", "html");

            javaMailSender.send(message1);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


        return "发送邮件！";
    }

    @RequestMapping(path = "/get/email")
    @ResponseBody
    public String check(HttpSession session, @RequestParam("code") String emailcode, @SessionAttribute("emailcode") String sessionemailcode) {

        if (emailcode.equals(sessionemailcode)) {
            session.removeAttribute("emailcode");
            return "验证成功！";
        } else
            return "验证失败！";

    }


}
